<?php

namespace fztadmin\modules\rbac\models\forms;

use common\models\db\AdminRolePower;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use yii\db\ActiveQuery;
use yii\db\Expression;
use yii\helpers\ArrayHelper;
use common\models\db\AdminRole as AdminRoleModel;

/**
* AdminRole represents the model behind the search form about `common\models\db\AdminRole`.
*/
class AdminRole extends AdminRoleModel
{
    public $has_is_checked_powers;
    public $has_is_selected_data_rules;

    public function attributeLabels()
    {
        $attributeLabels = parent::attributeLabels();
        $attributeLabels = ArrayHelper::merge($attributeLabels, []);
        return $attributeLabels;
    }

    public function rules()
    {
        $rules = parent::rules();
        /*foreach ($rules as $k => $v) {
            if ($v[1] == 'required'){
                $rules[$k][0] = array_diff($rules[$k][0], ['created_at', 'updated_at', 'created_by', 'updated_by']);
            }
        }*/
        $rules = ArrayHelper::merge($rules, [
            ['has_is_checked_powers',  "safe"],
            ['has_is_selected_data_rules',  "safe"],
        ]);
        return $rules;
    }

    public function setPowers()
    {
        $oldPowerIds = $this->getAdminPowerIds();
        $newPowerIds = $this->has_is_checked_powers;
        $delIds = array_diff($oldPowerIds, $newPowerIds);
        $addIds = array_diff($newPowerIds, $oldPowerIds);
        $newRolePower = new AdminRolePower();
        $newRolePower->admin_role_id = $this->id;
        foreach ($delIds as $k => $v) {
            $m = AdminRolePower::findOne(['admin_role_id' => $this->id, 'admin_power_id' => $v]);
            if (!$m->delete()){
                return false;
            }
        }
        foreach ($addIds as $k => $v) {
            $m = clone $newRolePower;
            $m->admin_power_id = $v;
            if (!$m->save()){
                return false;
            }
        }
        return true;
    }

    public function setDataRule()
    {
        $newDataRule = $this->has_is_selected_data_rules;
        foreach ($newDataRule as $k => $v) {
            $adminRolePower = AdminRolePower::findOne(['admin_role_id' => $this->id, 'admin_power_id' => $k]);
            $adminRolePower->data_rule = $v;
            if (!$adminRolePower->save()){
                return false;
            }
        }
        return true;
    }
}
